<template>
	<el-dialog v-model="visible" :title="step == 1 ? '选择商品' : '完善信息'" :width="step == 1 ? '80%' : '500px'" :before-close="handleClose">
		<ProTable
			:searchCol="{ xs: 1, sm: 2, md: 2, lg: 3, xl: 4 }"
			v-if="step == 1"
			ref="proTable"
			:columns="columns"
			:request-api="getTableList"
			:init-param="initParam"
			@current-change="handleCurrentChange"
			highlight-current-row
		>
			<template #expand="scope">
				{{ scope.row }}
			</template>
		</ProTable>
		<el-form ref="formRef" class="sync-form" v-if="step == 2" :model="form" :rules="rules" label-width="100px">
			<el-form-item label="平台类目" prop="categoryId">
				<el-cascader class="flex-grow mr10" v-model="form.categoryId" :options="typeOptions" :props="cascaderProps" />
			</el-form-item>
			<el-form-item label="发货时效" prop="shippingTimeLimit">
				<el-select class="flex-grow mr10" v-model="form.shippingTimeLimit">
					<el-option
						v-for="(item, index) in [
							'现货，用户付款后大于 72 小时发货',
							'现货，用户付款后 72 小时内发货',
							'现货，用户付款后 48 小时内发货',
							'现货，用户付款后次日发',
							'预售，付款后 7 天内发货',
							'预售，付款后 15 天内发货',
							'预售，付款后 30 天内发货',
						]"
						:label="item"
						:value="index + ''"
					/>
				</el-select>
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button v-if="step == 1" @click="handleClose">取消</el-button>
				<el-button v-if="step == 1" @click="toNext">下一步</el-button>
				<el-button
					v-if="step == 2"
					type="primary"
					@click="
						() => {
							step = 1;
						}
					"
					>上一步</el-button
				>
				<el-button v-if="step == 2" type="primary" :loading="submitLoading" v-debounce="submit">保存</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="tsx">
import { FormRules, ElMessage } from 'element-plus';
import { ref, reactive, watch, computed } from 'vue';
import ProTable from '../../../../../components/ProTable/index.vue';
import { fetchCreateSync, fetchGoodList, fetchTypeList, fetchTypeSync } from '/@/api/goods';
import { ProTableInstance, ColumnProps } from '../../../../../components/ProTable/interface';
import constant from '/@/utils/constant';
import { fenToYuan } from '/@/utils/commonFunction';
import Index from '../index.vue';

const props = defineProps({
	// 列表内容
	visible: {
		type: Boolean,
		default: () => false,
	},
	row: {
		type: Object,
		default: () => null,
	},
});

const emit = defineEmits(['handleClose']);

watch(
	() => props.visible,
	(val) => {
		visible.value = val;
	}
);

const step = ref(1);
const typeOptions = ref([]);
const cascaderProps = {
	label: 'name',
	value: 'id',
};

const submitLoading = ref(false);

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	paramCode: 'id',
});

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getTableList"
const getTableList = (params: any) => {
	let data = {
		...params,
		checkStatus: 3,
		syncAlipay: 1,
	};
	if (data.paramValue) {
		data[data.paramCode] = data.paramValue;
	}
	delete data.paramValue;
	delete data.paramCode;

	return fetchGoodList(data);
};

// 表格配置项
const columns: ColumnProps<any>[] = [
	{
		prop: 'paramValue',
		label: '商品搜索',
		isShow: false,
		search: {
			span: 3,
			xs: 1,
			sm: 1,
			md: 2,
			lg: 3,
			xl: 3,
			render: (scope: any) => {
				const slot = {
					prepend: () => (
						<el-select
							v-model={scope.searchParam.paramCode}
							placeholder="Select"
							style="width: 100px"
							onChange={(value) => (scope.searchParam.paramCode = value)}
						>
							{searchArr.map((item) => (
								<el-option key={item.value} label={item.label} value={item.value} />
							))}
						</el-select>
					),
				};
				return <el-input v-model={scope.modelValue} v-slots={slot} placeholder={getPlaceholder.value} maxlength={50}></el-input>;
			},
		},
	},
	{
		prop: 'id',
		label: '',
		minWidth: 50,
		render: (scope) => {
			return (
				<el-radio-group v-model={form.value.id}>
					<el-radio value={scope.row.id}></el-radio>
				</el-radio-group>
			);
		},
	},
	{
		prop: 'id',
		label: '商品ID',
	},
	{
		prop: 'name',
		label: '商品名称',
		minWidth: 300,
		render: (scope) => {
			return (
				<div class="flex-center">
					<el-image class="flex-shrink" src={scope.row.productImage.split(',')[0]} style="width:50px;height:50px"></el-image>
					<div class="ml10" style="text-align:left">
						<div class="ellipsis2">{scope.row.productName}</div>
						<div>物料编码：{scope.row.productCode}</div>
					</div>
				</div>
			);
		},
	},
	{
		prop: 'type',
		label: '商品类型',
		minWidth: 120,
		search: { el: 'select', props: { placeholder: '请选择商品类型', clearable: true, filterable: true } },
		enum: [
			{
				label: '实物',
				value: 0,
			},
			{
				label: '酒藏',
				value: 1,
			},
		],
		render(scope) {
			return scope.row.productType === 0 ? '实物' : '酒藏';
		},
	},
	{
		prop: 'productTypeId',
		label: '商品分类',
		minWidth: 120,
		search: { el: 'select', props: { placeholder: '请选择商品分类', clearable: true, filterable: true } },
		fieldNames: { label: 'name', value: 'id' },
		enum: () => {
			return new Promise<any>((resolve) => {
				fetchTypeList({ page: 1, size: 2000 }).then((res: any) => {
					resolve({
						code: 200,
						msg: 'success',
						data: res.data.records,
					});
				});
			});
		},
		render(scope) {
			return scope.row.productTypeName;
		},
	},
	{
		prop: 'status',
		label: '商品状态',
		minWidth: 120,
		render(scope: any) {
			return constant.GOODSTATUS[scope.row.status] || '';
		},
	},
	{
		prop: 'recommended',
		label: '是否推荐',
		minWidth: 120,
		search: { el: 'select', props: { placeholder: '请选择是否推荐', clearable: true, filterable: true } },
		enum: [
			{
				label: '是',
				value: 1,
			},
			{
				label: '否',
				value: 0,
			},
		],
		render: (scope) => {
			return scope.row.recommended ? '是' : '否';
		},
	},
	{
		prop: 'price',
		label: '价格',
		minWidth: 120,
		render: (scope) => {
			const price = scope.row.price?.split('-');
			if (!price) {
				return '--';
			}
			return `${fenToYuan(price[0])}${price[1] ? `-${fenToYuan(price[1])}` : ''}`;
		},
	},
	{
		prop: 'availableInventory',
		label: '库存',
		minWidth: 120,
	},
	{
		prop: 'order',
		label: '排序',
		minWidth: 120,
	},
];

const searchArr = [
	{
		label: '商品ID',
		value: 'id',
	},
	{
		label: '商品名称',
		value: 'name',
	},
	{
		label: '物料编码',
		value: 'materialCode',
	},
];

const getPlaceholder = computed(() => {
	const target = searchArr.find((item) => {
		return item.value == proTable.value?.searchParam.paramCode;
	});
	return target ? `输入${target?.label}搜索` : '';
});

const loading = ref(false);
const visible = ref(false);
const formRef = ref();
const form = ref<any>({});
//校验规则
const rules = reactive<FormRules<any>>({
	categoryId: [{ required: true, trigger: 'blur', message: '平台类目不能为空' }],
	shippingTimeLimit: [{ required: true, message: '发货时效不能为空', trigger: ['change', 'blur'] }],
});

const handleCurrentChange = (val: any) => {
	form.value = {
		...val,
	};
};

const toNext = async () => {
	if (!form.value.id) {
		ElMessage.error('请选择商品');
		return;
	}
	step.value = 2;
	const res = await fetchTypeSync({ type: form.value.productType });
	if (res.code == 200) {
		typeOptions.value = res.data;
	}
};

const submit = async () => {
	formRef.value.validate(async (valid: any) => {
		if (valid) {
			submitLoading.value = true;
			try {
				const res: any = await fetchCreateSync({ ...form.value, categoryId: form.value.categoryId.slice(-1)[0], productId: form.value.id });
				submitLoading.value = false;
				if (res.code == 200) {
					handleClose(true);
				}
			} catch (e) {
				submitLoading.value = false;
			}
		}
	});
};

const handleClose = (success?: boolean) => {
	form.value = {};
	if (formRef.value) {
		formRef.value.resetFields();
	}
	setTimeout(() => {
		step.value = 1;
	}, 500);
	emit('handleClose', success === true);
};
</script>

<style lang="scss">
.sync-form {
	.el-form-item {
		width: 100%;
	}
}
</style>
